package io.renren.common.utils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Value;

/**
 * 功能描述：
 *
 * @Author: lyc
 * @Date: 2022/12/11 12:27
 */
public class UploadUtils {
    @Value("${file-save-path}")
    public String fileSavePath;
    public static String uploadImage(MultipartFile file,HttpServletRequest request){

        try {
            //图片名后缀：.jpg、.png
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            //uuid
            String uuid = UUID.randomUUID().toString();
            //文件新名称
            String newFileName = uuid + suffix;

            //创建保存上传文件的文件夹 C:\bookImgUpload\
//            File folder = new File("/Users/ycl/Desktop/img/" + newFileName);
            File folder = new File("fileSavePath" + newFileName);
//            File folder = new File("C:\\bookImgUpload\\" + newFileName);
            if (!folder.getParentFile().exists()) {
                folder.getParentFile().mkdirs();
            }
            //文件写入到该文件夹下
            file.transferTo(folder);
            //获得本机Ip（获取的是服务器的Ip）
            InetAddress inetAddress = InetAddress.getLocalHost();
            String ip = inetAddress.getHostAddress();
            //返回保存的url，根据url可以进行文件查看或者下载
            String fileDownloadUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/renren-admin/images/" + newFileName;
            return fileDownloadUrl;
//            return "upload/"+datePath+"/"+newFilename;//资源映射路径
        } catch (IOException e) {
            e.printStackTrace();
            return "失败！";
        }
    }
}
